import { Component, EventEmitter, Injector, OnInit, Output, ViewChild } from '@angular/core';
import { AppModalComponentBase } from '@shared/common/app-modal-component-base';
import { Content2ServiceProxy, ContentRelate, ContentServiceProxy, GetAllMenusForTopicOperationInput, GetMenusForOperationInput, IEntityDtoOfGuid, MenuSampeInfo, PagedContentInput } from '@shared/service-proxies/service-proxies';
import { BsModalRef } from 'ngx-bootstrap/modal';
import { LazyLoadEvent } from 'primeng/api';
import { Paginator } from 'primeng/paginator';
import { Table } from 'primeng/table';
import { finalize } from 'rxjs/operators';
import { ISelectInfoItemOption } from './select-info-item-option';
import { ISelectedMenu, ISelectedMenuList } from './selected-menu-list';

@Component({
    templateUrl: './sharing-info2-modal.component.html'
})
export class SharingInfo2ModalComponent  extends AppModalComponentBase {
  title = "选择栏目";
  typeSelect = false;


  isLoading = false;
  saving = false;
  kind: number;
  key: string;
  id: string;
  operationType: number;
  relateId: string;

  option: ISelectInfoItemOption;

  menuData: MenuSampeInfo[] = [];
  typeList = [{ name: '信息链接', value: 1 }, { name: '信息引用（分享编辑权限）', value: 0 }];
  ztMenuData: MenuSampeInfo[] = [];
  selectedMenus: MenuSampeInfo[] = [];
  selectedZtMenu: number = 0;

  selectedZt = [];

  data: ISelectedMenuList = {
    toMenus: [],
    toMenus2:[],
    toMenuNames: [],
    toMenuNames2: [],
    managementType: 1,
    success: false
  };

  callBack: { (data: ISelectedMenuList): void };

  selectedZtRows: IEntityDtoOfGuid[] = [];

  constructor(
    public bsModalRef: BsModalRef,
    injector: Injector,
    private _contentService: ContentServiceProxy,
    private _content2Service: Content2ServiceProxy) {
    super(injector);
  }

  shown() {
    this.typeSelect = false;

    if (this.option.type) {
      this.title = this.l(this.option.type);
      this.typeSelect = true;
    }

    this.kind = this.option.kind;
    this.key = this.option.customKey;
    this.id = this.option.id;
    this.operationType = 2;  //分享

    if (this.option.relateId) {
      this.relateId = this.option.relateId;
    } else {
      this.relateId = null;
    }

    this.requestParams = new PagedContentInput();
    this.requestParams.relateId = this.relateId;
    this.requestParams.menuId = 0;
    this.requestParams.customKey = this.key;
    this.filter = "";

    this.init();
  }

  init() {
    this.isLoading = true;
    this._content2Service.getMenusForOperation(new GetMenusForOperationInput({
      id: this.id,
      menuId: this.kind,
      customKey: this.key,
      operationType: this.operationType
    })).pipe(finalize(() => this.isLoading = false))
      .subscribe(result => {
        this.menuData = result.items;
        if (this.option.selected && this.option.selected.length > 0) {
          this.menuData.forEach((value, index) => {
            this.option.selected.forEach((value2, index2) => {
              if (value.auxiliaryId === value2) {
                this.selectMenus(value);
              }
            });
          });
        }
      });

    //专题栏目，可用参数customKey主动传入专题的配置key，不传则自动查找
    this._content2Service.getAllMenusForTopicOperation(new GetAllMenusForTopicOperationInput({
      customKey: null,
      customKey2: this.key
    })).pipe(finalize(() => this.isLoading = false))
      .subscribe(result => {
        this.ztMenuData = result.items;
        if (this.ztMenuData.length > 0) {
          this.selectedZtMenu = this.ztMenuData[0].auxiliaryId;
          this.selectZtMenus(this.ztMenuData[0]);
        }
      });
  }

  save() {
    if (this.data.toMenus.length === 0 && this.data.toMenus2.length === 0) {
      this.data.success = false;
    } else {
      this.data.success = true;
    }

    const data: ISelectedMenuList = {
      managementType: this.data.managementType,
      toMenus: this.data.toMenus.concat(this.data.toMenus2),
      toMenuNames: this.data.toMenuNames.concat(this.data.toMenuNames2),
      success: this.data.success,
      toMenus2: [],
      toMenuNames2 : []
    };

    this.callBack(data);
    this.close();
  }

  close(): void {
    this.bsModalRef.hide();
  }

  selectMenus(menu) {
    for (let i = 0; i < this.selectedMenus.length; i++) {
      if (this.selectedMenus[i].auxiliaryId === menu.auxiliaryId) {
          return;
      }
    }

    this.selectedMenus.push(menu);
    this.data.toMenus.push(new ContentRelate({ menuId: menu.auxiliaryId, relateId: null}));
    const menuName = menu.path.split(' / ');
    this.data.toMenuNames.push(menuName[menuName.length - 1]);
  };
  removeSelectedMenus(menu) {
    //if (item.required) {
    //    abp.notify.warn(item.surname + "是必选项，不能移除");
    //    return;
    //}

    let i = -1;
    this.selectedMenus.forEach((value, index) =>{
        if (value.auxiliaryId === menu.auxiliaryId) {
            i = index;
        }
    });
    if (i > -1) {
      this.selectedMenus.splice(i, 1);
      this.data.toMenus.splice(i, 1);
      this.data.toMenuNames.splice(i, 1);
    }
  };

  // 专题查询
  selectZtMenus(menu) {
    this.requestParams.menuId = menu.auxiliaryId;
    this.requestParams.customKey = menu.customKey;
    this.requestParams.skipCount = 0;
    this.requestParams.filter = "";
    this.refreshGrid();
  };

  filter: string = '';
  requestParams: PagedContentInput;

  @ViewChild('dataTable', { static: true }) dataTable: Table;
  @ViewChild('paginator', { static: true }) paginator: Paginator;

  refreshGrid(event?: LazyLoadEvent) {
    if (this.requestParams.menuId === 0) {
      this.primengTableHelper.totalRecordsCount = 0;
      this.primengTableHelper.records = [];
      return;
    }

    if (this.primengTableHelper.shouldResetPaging(event)) {
      if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
        return;
      }
    }

    this.primengTableHelper.showLoadingIndicator();
    this._contentService.getContentListByPaged(this.requestParams)
      .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe((result) => {
        this.primengTableHelper.totalRecordsCount = result.totolCount;
        this.primengTableHelper.records = result.items;
        this.primengTableHelper.hideLoadingIndicator();
        this.selectedZtRows = [];
        this.selectedZt.length = 0;
      });
  };
}
